import React, { Component } from 'react';
import { connect } from 'dva';
import { Icon, Button, Table, Modal, Row, Col, Input, Select, Form, Upload, Radio, Pagination } from 'antd';
import {withPropsAPI} from "gg-editor";
import { FormattedMessage } from 'umi-plugin-react/locale';
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});
import styles from "../../../KnowledgeManagement/AntistopReply/index.less";
import {message} from "antd/lib/index";
import axios from "axios/index";

@connect(({ dialogCommon, loading }) => ({
  dialogCommon,
  loading: loading.models.data,
}))
class DialogSlotMark extends React.Component {

  getInit = ()=>{
    const { nodeId, dialogId, stage } = this.state;
    console.log("nodeId: " + nodeId + ", dialogId :" + dialogId);
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/getStage',
      payload: {
        dialogId: dialogId,
        nodeId: nodeId,
        stage: stage,
        field: "mark",
      },
      callback:(res)=>{
        console.log("收集词槽-用户语料标注 :" + JSON.stringify(res));
        console.log("mark :" + res.dialogStage.mark);
        this.setState({
          mark: res.dialogStage.mark==null?[]:res.dialogStage.mark,
          slots: res.dialogSlots,
          stageId: res.dialogStage._id,
        });
      }
    });
  };

  componentDidMount() {
    this.getInit();
  };

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      visibleUpload: false,
      stageId: "",
      dialogId: props.dialogId,
      nodeId: props.nodeId,
      stage: props.stage,
      mark: [],
      word:{
        question : "",
        words : [],
        //markAs+filterRule字段内容筛选所用
        //markAs: "",
        //filterRule: "",
        //isConfirm字段信息确认所用
        isConfirm: true,
      },
      slots:[],
      markSlots:[],
      operaType: "",
      index: -1,
      currentPage: 1,
      pageSize: 10,
      fileList: [],
      uploading: false,
    };
  }

  handleDeletes = (item) =>{
    let { word } = this.state;
    const words = word.words;
    for (let i = 0; i < words.length; i++) {
      if(words[i] === item){
        words.splice(i, 1);
        break
      }
    }
    word["words"] = words;
    this.setState({
      word: word
    });
  };

  editMark = (item, index) =>{
    console.log("item :" + JSON.stringify(item));
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/splitWord',
      payload: {
        question: item.question,
      },
      callback:(res)=>{
        console.log("编辑时分词结果:" + JSON.stringify(res));
        this.setState({
          markSlots: res,
          word: item,
          visible: true,
          operaType: "edit",
          index: index,
        })
      }
    });
  };

  wordsWordChange = (e, item) =>{
    let { word } = this.state;
    const words = word.words;
    for (let i = 0; i < words.length; i++) {
      if(words[i] === item){
        words[i]["word"] = e.target.value;
        break
      }
    }
    word["words"] = words;
    this.setState({
      word: word
    });
  };

  addWord = (item) =>{
    let { word } = this.state;
    const words = word.words;
    words.push({word:item,slotId:""});
    word["words"] = words;
    this.setState({
      word: word
    });
  };

  changeSlots = (val,index,valType) =>{
    const { word } = this.state;

    switch (valType){
      case "slot":
        word.words[index].slotId = val;
        break;
      case "markAs":
        word.words[index].markAs = val;
        break;
      case "filterRule":
        word.words[index].filterRule = val;
        break;
    }

    console.log("word :" + JSON.stringify(word));
    this.setState({
      word: word,
    })
  };

  changeQuestion = (event) =>{
    const { dispatch } = this.props;
    const { word } = this.state;
    word["question"] = event.target.value;
    this.setState({
      word: word
    },()=>{
      if(this.state.word.question.trim() !== ""){
        dispatch({
          type: 'dialogCommon/splitWord',
          payload: {
            question: this.state.word.question,
          },
          callback:(res)=>{
            this.setState({
              markSlots: res,
            })
          }
        });
      }
    });
  };

  save = (saveType) =>{
    const { operaType,index,mark,word,stageId } = this.state;
    const { dispatch } = this.props;
    console.log("type :" + operaType + ", index :" + index);
    let obj = {};
    switch (this.state.stage){
      case "confirm":
        obj = {
          question: word.question,
          isConfirm: word.isConfirm,
        };
        break;
      default:
        obj = {
          question: word.question,
          words: word.words,
        };
        break;
    }
    if(operaType == "add"){
      mark.unshift(obj);
      dispatch({
        type: 'dialogCommon/saveStage',
        payload: {
          _id: stageId,
          field: "mark",
          mark: mark,
        },
        callback:(res)=>{
          if(res.code === 0){
            message.info("保存成功");
          }else{
            message.info("保存失败");
          }
          console.log("新增语料标注结果 :" + JSON.stringify(res));
        }
      });
    }else{
      mark[index] = obj;
      dispatch({
        type: 'dialogCommon/saveStage',
        payload: {
          _id: stageId,
          field: "mark",
          mark: mark,
        },
        callback:(res)=>{
          console.log("编辑语料标注结果 :" + JSON.stringify(res));
          if(res.code === 0){
            message.info("保存成功");
          }else{
            message.info("保存失败");
          }
        }
      });
    }

    if(saveType === "next"){
      console.log("mark.length :" + mark.length);
      if(index != -1 && index < mark.length-1){
        this.editMark(mark[index+1], index+1);
      }else{
        this.setState({
          word:{
            question: "",
            words: [],
            isConfirm: true,
          },
          operaType: "add",
          markSlots: [],
        })
      }
    }else{
      this.setState({
        visible: false,
      })
    }
  };

  removeMark = (index) =>{
    const { mark,stageId,currentPage,pageSize } = this.state;
    console.log("index :" + index + ",currentPage" + currentPage + ", pageSize:" + pageSize);
    const { dispatch } = this.props;
    mark.splice((currentPage-1)*pageSize+index, 1);
    dispatch({
      type: 'dialogCommon/saveStage',
      payload: {
        _id: stageId,
        field: "mark",
        mark: mark,
      },
      callback:(res)=>{
        console.log("删除语料标注结果 :" + JSON.stringify(res));
        if(res.code === 0){
          message.info("删除成功");
          if(currentPage > ((mark.length + pageSize - 1)/pageSize)){
            this.setState({
              currentPage: currentPage-1
            })
          }
        }else{
          message.info("删除失败");
        }
      }
    });
  };

  handleSubmitComment = (val) =>{
    console.log("handleSubmitComment :" + val);
    this.setState({
      currentPage: val,
    })
  };

  changePageSize = (val) =>{
    console.log("changePageSize :" + val);
    this.setState({
      pageSize: val,
    })
  }

  handleCancelVisibleUpload = () =>{
    this.setState({
      visibleUpload: false,
    })
  };

  uploadMark = () =>{
    this.setState({
      visibleUpload: true,
    })
  };

  changeMarkRadio = (event) =>{
    console.log(" value :" + event.target.value);
    const { word } = this.state;
    word["isConfirm"] = event.target.value;
    this.setState({
      word
    })
  };

  handleOk = (e) => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('file', file.originFileObj);
      formData.append("name", file.name);
      formData.append("dialogId", this.state.stageId);
      formData.append("stageType", "slot");
    });
    this.setState({
      uploading: true
    });
    this.uploadFile(formData);
  };

  uploadFile=(data)=>{
    const robotId = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).robotId;
    const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token ;
    axios.post('/cloud/dialog/importCorpus', data, {
      method: 'post',
      processData: false,
      headers: {'Content-Type': 'multipart/form-data;charset=UTF-8',"token":token,'robotId':robotId}
    }).then((res) => {
      this.setState({
        uploading:false
      },()=>{
        if(res.data.code){
          return message.error(res.data.msg)
        }else{
          this.setState({
            visibleUpload:false,
            fileList:[]
          },()=>{
            message.success('导入成功');
            this.getInit();
          });

        }
      })
    }).catch((error) => {
      message.error('导入失败请稍等再试')
    });
  };

  handleUpFile = (info) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    if (fileList[0].size > 2000000) { // 2000000
      message.error('上传文件超出2M')
      this.setState({ fileList:[] });
    }else{
      this.setState({ fileList});
    }
  };

  render() {
    const columns = [
      {
        title: '语料',
        width: 'calc(60vw)',
        dataIndex: 'question'
      },
      {
        title: '标注状态',
        width: 'calc(60vw)',
        render: (item) => {
          return(
            this.state.stage === "confirm"?<div>{item.isConfirm ?"确认":"不确认"}</div>:<div>{item.words.length>0 ?"已标注":"未标注"}</div>
          )
        }
      },
      {
        title: '操作',
        width: 'calc(20vw)',
        render: (text,item,index) => {
          return <div className={styles.pb}>
            <div
              onClick={() => this.editMark(item, index)}
              className={styles.buttongl}>
              <MyIcon style={{ marginRight: 5 }} type="icon-bi" />
              <FormattedMessage id="app.dialog.collect.mark" defaultMessage="Edit" />
            </div>
            <div
              onClick={() => this.removeMark(index)}
              style={{ marginLeft: 10, background: '#e8313b' }}
              className={styles.buttongl}>
              <span><Icon size="small" type='delete' style={{ marginRight: 5 }} />
              </span><span> <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" /></span>
            </div>
          </div>
        }
      }
    ]

    //标注部分
    const columns2 = [
      {
        title: '取词',
        width: '40%',
        render: (item) => {
          return(
            <div>
              <Input placeholder="default size" value={item.word} onChange={event=>{this.wordsWordChange(event, item)}}/>
            </div>
          )
        }
      },
      {
        title: '所属词槽',
        width: '40%',
        render: (text,item,index) => {
          return(
            <div>
              <Select value={item.slotId} style={{ width: '140px' }} onChange={(value) => this.changeSlots(value,index,"slot")}>
                {
                  this.state.slots.map((slot)=>(
                    <Select.Option value={slot.slotId}>{slot.slotName}</Select.Option>
                  ))
                }
              </Select>
            </div>
          )
        }
      },
      {
        title: '操作',
        width: '20%',
        render: (item) => {
          return <div className={styles.pb}>
            <div
              style={{ background: '#e8313b' }}
              onClick={() => { this.handleDeletes(item) }}
              className={styles.buttongl}>
              <span><Icon size="small" type='delete' style={{ marginRight: 5 }} />
              </span><span> <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" /></span>
            </div>
          </div>
        }
      }
    ]

    //标注部分
    const columns3 = [
      {
        title: '取词',
        width: '25%',
        render: (item) => {
          return(
            <div  style={{ width: '100px' }}>
              <Input placeholder="default size" value={item.word} onChange={event=>{this.wordsWordChange(event, item)}}/>
            </div>
          )
        }
      },
      {
        title: '类型',
        width: '20%',
        render: (text,item,index) => {
          return(
            <div>
              <Select style={{ width: '80px' }} value={item.markAs} onChange={(value) => this.changeSlots(value,index,"markAs")}>
                <Select.Option value="none">请选择</Select.Option>
                <Select.Option value="slot">词槽</Select.Option>
                <Select.Option value="filter">筛选规则</Select.Option>
              </Select>
            </div>
          )
        }
      },
      {
        title: '所属词槽',
        width: '20%',
        render: (text,item,index) => {
          return(
            <div>
              <Select value={item.slotId} style={{ width: '80px' }} onChange={(value) => this.changeSlots(value,index,"slot")}>
                {
                  this.state.slots.map((slot)=>(
                    <Select.Option value={slot.slotId}>{slot.slotName}</Select.Option>
                  ))
                }
              </Select>
            </div>
          )
        }
      },
      {
        title: '筛选规则',
        width: '20%',
        render: (text,item,index) => {
          return(
            <div>
              <Select style={{ width: '80px' }} value={item.filterRule} onChange={(value) => this.changeSlots(value,index,"filterRule")} disabled={item.markAs==="slot"?true:false}>
                <Select.Option value="none">请选择</Select.Option>
                <Select.Option value="lt">小于</Select.Option>
                <Select.Option value="gt">大于</Select.Option>
                <Select.Option value="max">最大值</Select.Option>
                <Select.Option value="min">最小值</Select.Option>
                <Select.Option value="range">区间</Select.Option>
                <Select.Option value="not_contain">不包含</Select.Option>
                <Select.Option value="not_eq">不等于</Select.Option>
                <Select.Option value="eq">等于</Select.Option>
              </Select>
            </div>
          )
        }
      },
      {
        title: '操作',
        width: '15%',
        render: (item) => {
          return <div className={styles.pb}>
            <div
              style={{ background: '#e8313b' }}
              onClick={() => { this.handleDeletes(item) }}
              className={styles.buttongl}>
              <span><Icon size="small" type='delete' style={{ marginRight: 5 }} />
              </span><span> <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" /></span>
            </div>
          </div>
        }
      }
    ]

    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 },
      },
    };

    const props = {
      // name: 'file',
      // headers: headData,
      // action: '/cloud/new/basic/lexicon/import',
      // accept: '.xlsx',
      // onChange: this.handleChangeByUpload,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      accept: '.xlsx',
      onChange: this.handleUpFile,
    }

    return(
      <div>
        <div style={{marginBottom:'20px'}}>
          <Button onClick={this.addMark} type='primary' icon="plus" style={{padding:'0px 7px', marginRight:'10px'}}>添加语料</Button>
          <Button onClick={this.uploadMark} type='primary' icon="plus" style={{backgroundColor:'white', color:'#2AC6F4',padding:'0px 7px'}}>导入语料</Button>
        </div>

        <div>
          <Table
            columns={columns}
            dataSource={this.state.mark}//数据
            pagination={false} //分页设置
          />
          <Pagination
            style={{ textAlign: 'center', marginTop: 20 }}
            total={this.state.mark.length}
            pageSize={this.state.pageSize}
            current={this.state.currentPage}
            showSizeChanger={true}
            onChange={this.handleSubmitComment}
            onShowSizeChange={this.changePageSize}
            showTotal={() => `共 ${this.state.mark.length} 条`}
          />
        </div>

        <Modal
          title="添加/编辑语料"
          visible={this.state.visible}
          onCancel={this.close}
          width={this.state.stage === "filter"?'600px':'520px'}
          footer={[
            <Button key={1} onClick={this.close}>
              取消
            </Button>,
            <Button key={2} type="primary" onClick={() =>this.save("next")}>
              保存&下一个
            </Button>,
            <Button key={3} type="primary" onClick={() =>this.save("this")}>
              保存
            </Button>,
          ]}
        >
          <Row>
            <Col span={24}>
              <div style={{ marginBottom: '20px' }}>回复话术&nbsp;&nbsp;<Input style={{width:'85%', height: '30px'}} placeholder="" value={this.state.word.question} onChange={event=>{this.changeQuestion(event)}}/></div>

              {
                this.state.stage === "confirm"?
                  <div style={{ marginBottom: '20px',paddingLeft:'28px' }}>
                    标注&nbsp;&nbsp;
                    <Radio.Group value={this.state.word.isConfirm} onChange={event=>{this.changeMarkRadio(event)}}>
                      <Radio value={true}>确认</Radio>
                      <Radio value={false}>不确认</Radio>
                    </Radio.Group>
                  </div>
                  :
                  <div>
                    <div style={{ marginBottom: '20px' }}>标注词槽&nbsp;&nbsp;
                      {
                        this.state.markSlots.map((item, index) =>
                          <Button type="primary" style={{ padding: '0 10px', marginRight: '10px'}} onClick={() => this.addWord(item)}>{item}</Button>
                        )
                      }
                    </div>

                    <div visible={false} style={{ marginBottom: '20px' }}>
                      <Table
                        columns={this.state.stage==="filter"?columns3:columns2}
                        pagination={false}
                        dataSource={this.state.word.words}//数据
                      />
                    </div>
                  </div>
              }

            </Col>
          </Row>
        </Modal>

        <Modal
          title="导入标记语料"
          visible={this.state.visibleUpload}
          onCancel={this.handleCancelVisibleUpload}
          width='630px'
          centered
          footer={[
            <Button key="back" onClick={this.handleCancelVisibleUpload}>
              取消
            </Button>,
            <Button key="submit" type="primary" loading={this.state.loading} disabled={this.state.fileList.length === 0} onClick={this.handleOk}>
              {false ? '导入中' : '开始导入'}
            </Button>,
          ]}
        >
          <Form {...formItemLayout}>
            <Form.Item label={<FormattedMessage id="app.overView.file"/>}>
              <Upload {...props} fileList={this.state.fileList}>
                <Button>
                  <Icon type="upload" /> <FormattedMessage id="app.overView.file"/>
                </Button>
              </Upload>
            </Form.Item>
            <Form.Item label={<FormattedMessage id="app.overView.file"/>}>
              <div style={{ border: '1px solid grey', padding: 10, borderRadius: 10, overflow: 'hidden' }}>
                <div>•上传文件格式为.xlsx：<span style={{color:'blue',cursor:'pointer'}}>下载xlsx模板</span></div>
              </div>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  };

  addMark = () => {
    this.setState({
      visible: true,
      word:{
        question : "",
        words : [],
        isConfirm: true,
      },
      markSlots: [],
      operaType: "add",
    });
  };

  close = () => {
    this.setState({ visible: false });
  }
}

export default withPropsAPI(DialogSlotMark);
